package com.rd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rd.pojo.MenuRole;
import com.rd.pojo.Role;
import com.rd.service.IMenuRoleService;
import com.rd.service.IMenuService;
import com.rd.service.IRoleService;
import com.rd.util.ResultModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统管理
 */
@RestController
@RequestMapping("/system/role")
public class RoleController {

    @Resource
    private IRoleService roleService;

    @Resource
    private IMenuService menuService;

    @Resource
    private IMenuRoleService menuRoleService;

    @ApiOperation(value = "获取所有角色")
    @GetMapping("/roleList")
    public ResultModel getAllRoles(){
        return ResultModel.createBySuccess().put("roleList",roleService.list());
    }

    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/menuList")
    public ResultModel getAllMenus(){
        return ResultModel.createBySuccess().
                put("menuList",menuService.getAllMenus());
    }

    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid))
                .stream().map(MenuRole::getMid).collect(Collectors.toList());
    }


    @ApiOperation(value = "添加角色")
    @PostMapping("/addRole")
    public ResultModel addRole(@RequestBody Role role){
        //判断英文角色名称是否需要添加前缀
        if(!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if(roleService.save(role)){
            return ResultModel.createBySuccess("角色添加成功！");
        }
        return ResultModel.createBySuccess("角色添加失败！");
    }


    @ApiOperation(value = "更新角色菜单")
    @PostMapping("/updateMenuRole")
    public ResultModel updateMenuRole(Integer rid,Integer[] mids){
        /*rid 角色id   mids数组 权限id数组*/
        return menuRoleService.updateMenuRole(rid,mids);
    }


    @ApiOperation(value = "删除角色")
    @GetMapping("/deleteRole/{rid}")
    public ResultModel deleteRole(@PathVariable Integer rid){
        List<MenuRole> list = menuRoleService
                .list(new QueryWrapper<MenuRole>().eq("rid", rid));
        if(list!=null && list.size()>0){
           return  ResultModel.createByErrorCodeMessage("此角色授予权限不能删除！");
        }
        if(roleService.removeById(rid)){
            return ResultModel.createBySuccess("删除成功！");
        }
        return ResultModel.createByErrorCodeMessage("删除失败！");
    }

}
